package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.user.UserFeignClient;
import com.heima.comment.dtos.CommentRepayDto;
import com.heima.comment.dtos.CommentRepayLikeDto;
import com.heima.comment.dtos.CommentRepayListDto;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.vos.ApCommentVo;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private GreenTextScan textScan;

    /**
     * 保存回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentRepayDto dto) {
        //1.检查参数
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }

        //2.判断是否登录
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.5 判断如果是游客身份则不允许发表回复
        if(apUser.getId()==0){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"请登录之后再来评论！！");
        }

        //3.查询用户信息------先从redis中查询，如果不存在再从用户微服务中去查询
        String apUserStr = redisTemplate.opsForValue().get("LOGIN_USER_" + apUser.getId());
        if(apUserStr != null){
            apUser = JSON.parseObject(apUserStr, ApUser.class);
        }else{
            ResponseResult<ApUser> feignClientUser = userFeignClient.findUserById(apUser.getId().longValue());
            if(feignClientUser.getCode() == 200){
                apUser = feignClientUser.getData();
                //存到redis
                redisTemplate.opsForValue().set("LOGIN_USER_"+apUser.getId(), JSON.toJSONString(apUser),2, TimeUnit.HOURS);
            }else{
                return ResponseResult.errorResult(feignClientUser.getCode(),feignClientUser.getErrorMessage());
            }
        }

        //回复内容审核
        /*if(!scanTextFilter(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }*/

        //保存数据到mongodb中
        saveCommentToMongo(dto, apUser);

        //回复数量显示也要处理
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        Update update = new Update().inc("reply", 1);
        mongoTemplate.updateFirst(query,update,ApComment.class);

        return ResponseResult.okResult("回复成功");
    }

    /**
     * 回复保存到mongodb的封装
     * @param dto
     * @param apUser
     */
    private void saveCommentToMongo(CommentRepayDto dto, ApUser apUser) {
        ApComment apComment = new ApComment();
        apComment.setId(ObjectId.get().toHexString());
        apComment.setUserId(apUser.getId());
        apComment.setNickName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setTargetId(dto.getCommentId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        mongoTemplate.insert(apComment);
    }


    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 评论内容审核
     * @param content
     * @return
     */
    private boolean scanTextFilter(String content) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map != null && !map.get("suggestion").equals("pass")) {//表示违规
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 点赞评论方法
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        //1.检查参数
        if (dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.判断是否登录
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.判断评论是否存在
        ApComment comment = mongoTemplate.findById(dto.getCommentRepayId(), ApComment.class);
        if (comment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //设置redis的key
        String key="COMMENT_REPAY_LIKE_"+user.getId();
        //查询redis是否包含该评论id的点赞
        Boolean isLike = redisTemplate.opsForSet().isMember(key, dto.getCommentRepayId());

        //非法操作
        if((isLike && dto.getOperation() == 0) || (!isLike && dto.getOperation() == 1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"非法操作");
        }
        //正常取消点赞
        if(isLike && dto.getOperation() == 1){
            //删除redis
            redisTemplate.opsForSet().remove(key,dto.getCommentRepayId());
            //删除mongodb
            mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId())
                    .and("targetId").is(dto.getCommentRepayId())), ApCommentLike.class);
            //更新comment
            Query query = Query.query(Criteria.where("id").is(comment.getId()).and("likes").gt(0));
            Update update = new Update().inc("likes", -1);
            mongoTemplate.updateFirst(query,update,ApComment.class);
        }
        //正常点赞
        if(!isLike && dto.getOperation() == 0){
            //添加redis
            redisTemplate.opsForSet().add(key,dto.getCommentRepayId());
            //添加mongodb
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setId(ObjectId.get().toHexString());
            apCommentLike.setTargetId(dto.getCommentRepayId());
            apCommentLike.setUserId(user.getId());
            apCommentLike.setCreatedTime(new Date());
            mongoTemplate.save(apCommentLike);
            //更新comment表
            Query query = Query.query(Criteria.where("id").is(comment.getId()));
            Update update = new Update().inc("likes", 1);
            mongoTemplate.updateFirst(query,update,ApComment.class);
        }
        //更新comment数据给前台
        comment = mongoTemplate.findById(comment.getId(), ApComment.class);
        Map map = new HashMap();
        map.put("likes",comment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 根据评论id去查询所有的评论回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayListDto dto) {
        //校验参数
        if(dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getSize() == null || dto.getSize() <= 0){
            dto.setSize(10);
        }
        //最大显示50条
        dto.setSize(Math.min(50,dto.getSize()));
        //根据文章id查询mongodb的回复信息,分页降序排序
        Query query = Query.query(Criteria.where("targetId").is(dto.getCommentId())
                        .and("createdTime").lt(dto.getMinDate())).with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getSize());
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        if(commentList == null || commentList.size() < 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //如果是游客登录,直接返回回复列表,无需判断点赞情况
        ApUser apUser = ApThreadLocalUtil.getUser();
        if(apUser.getId() == 0){
            return ResponseResult.okResult(commentList);
        }
        //如果是用户登录,就要判断点赞状态
        //查询redis点赞数据
        String key="COMMENT_REPAY_LIKE_" + apUser.getId();
        Set<String> like_ids = redisTemplate.opsForSet().members(key);
        if(like_ids == null){
            //不作处理,直接返回回复列表
            return ResponseResult.okResult(commentList);
        }
        //存在点赞数据,要返回标记
        List<ApCommentVo> list = commentList.stream().map(comment -> {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(comment, vo);
            if (like_ids.contains(comment.getId())) {
                vo.setOperation((short) 0);
            }
            return vo;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(list);
    }
}
